package com.heima.user.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.user.dto.LoginDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author dxx
 * @since 2022-09-19
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        // 参数校验
        if (dto == null || (
                StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getEquipmentId())
        )) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 如果手机号和密码不为空,使用手机号和密码登录
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            // 使用手机号查询用户
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(query);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 获取用户的盐
            String salt = one.getSalt();
            // 拼接进行MD5计算
            String pass = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            // 跟数据库中的密码进行对比
            if (pass.equals(one.getPassword())) {
                // 使用用户信息生成token
                Map<String, Object> claimMap = new HashMap<>();
                claimMap.put("userId", one.getId());
                String token = AppJwtUtil.getToken(claimMap);
                Map<String, Object> result = new HashMap<>();
                one.setPhone(null);
                one.setPassword(null);
                one.setSalt(null);
                result.put("user", one);
                result.put("token", token);
                return ResponseResult.okResult(result);
            }
        }
        // 如果设备ID不为空,使用游客的身份登录,使用0来生成token
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> claimMap = new HashMap<>();
            claimMap.put("userId", 0);
            String token = AppJwtUtil.getToken(claimMap);
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            return ResponseResult.okResult(result);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}
